package com.atmilan.quartz.utils.source;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.atmilan.quartz.constant.enums.BarCodeEnum;
import com.atmilan.quartz.constant.enums.CategoryTypeEnum;
import com.atmilan.quartz.constant.enums.ProductTypeEnum;
import com.atmilan.quartz.constant.enums.StockAreaTempEnum;
import com.atmilan.quartz.model.dto.crmeb.StoreProductCrmebRequest;
import com.atmilan.quartz.model.entity.buyer.Supplier;
import com.atmilan.quartz.model.entity.coltorti.ColtortiProduct;
import com.atmilan.quartz.model.entity.crmeb.CategoryMatch;
import com.atmilan.quartz.model.entity.crmeb.StoreBrand;
import com.atmilan.quartz.model.entity.crmeb.StoreProductAttr;
import com.atmilan.quartz.model.entity.crmeb.SupplierDiscount;
import com.atmilan.quartz.model.entity.hiqer.HiQErProduct;
import com.atmilan.quartz.model.result.PriceResult;
import com.atmilan.quartz.service.ICategoryMatchService;
import com.atmilan.quartz.service.IStoreBrandService;
import com.atmilan.quartz.service.ISupplierService;
import com.atmilan.quartz.service.SupplierDiscountService;
import com.atmilan.quartz.sync.push.crmeb.domain.StoreProductAttrValueRequest;
import com.atmilan.quartz.sync.push.crmeb.enums.CrmebMerchantEnums;
import com.atmilan.quartz.utils.PriceUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;

/**
 * 处理源数据转换和计算相关信息
 * @Description: 
 * @author daigb
 * @date 2021-03-05
 */
@Service
public class SourceHiQErProductUtil {
    @Autowired
    IStoreBrandService storeBrandService;
    @Autowired
    ICategoryMatchService categoryMatchService;
    @Autowired
    ISupplierService supplierService;
    @Autowired
    PriceUtil priceUtil;
    @Autowired
    SupplierDiscountService supplierDiscountService;

    /**
     * 构建DO对象
     * @Description:  
     * @author daigb 
     * @param @param product
     * @param @param productSkus
     * @param @return
     * @return StoreProductRequest
     * @throws
     */
    public StoreProductCrmebRequest buildColtortiProduct(HiQErProduct product) {
        // 主商品对象
        StoreProductCrmebRequest productRequest = new StoreProductCrmebRequest();
        String keyword = product.getGoodsItem();

        try {
            // 轮播图
            JSONArray gallery = new JSONArray();
//            if(StringUtil.isNotEmpty(product.getImage())) {
//                gallery.add(product.getImage());
//            }

            // 主图
//            String mainImage = gallery.getString(0);
            // 原价
            BigDecimal otPrice = product.getCostPrice();
            // 成本价
            BigDecimal price = product.getRetailPrice();

            // 品牌对应
            StoreBrand buyerStoreBrand = storeBrandService.getOne(Wrappers.<StoreBrand>lambdaQuery()
                    .eq(StoreBrand :: getEnName, product.getBrand())
                    .eq(StoreBrand :: getType, ProductTypeEnum.HIQER)
                    .last("LIMIT 1")
            );
            // 未匹配品牌记录
            storeBrandService.unMatchBrand(buyerStoreBrand,null,product.getBrand(),ProductTypeEnum.HIQER);
            StoreBrand storeBrand = null;
            if(null != buyerStoreBrand) {
                if(null != buyerStoreBrand.getSuperId()) {
                    storeBrand = storeBrandService.getById(buyerStoreBrand.getSuperId());
                } else {
                    storeBrand = storeBrandService.getById(5429);
                }
            } else {
                storeBrand = storeBrandService.getById(5429);
            }

            // 供应商
            Supplier supplier = supplierService.getOne(Wrappers.<Supplier>lambdaQuery()
                    .eq(Supplier :: getBarcode, BarCodeEnum.HIQER.getCode())
                    .last("LIMIT 1")
            );
            if(null != supplier) {
                productRequest.setSuppliersId(supplier.getId());
                productRequest.setSuppliersName(supplier.getSuppliersName());
            }

            // 计算汇率和处理税率
//            otPrice = otPrice.multiply(new BigDecimal("1.22")).setScale(2, BigDecimal.ROUND_HALF_UP);
            PriceResult priceResult = priceUtil.eur2Rmb(price);
            price = priceResult.getPrice();

            /***** 处理对象构建 *******/
            // 最后一位标识是否为跨境 1：不是 2：是
            String barCode = BarCodeEnum.HIQER.getCode() + product.getGoodsItem() + product.getIsCrossBorder();
            List<StoreProductAttr> attrList = new ArrayList<>();
            List<StoreProductAttrValueRequest> attrValueList = new ArrayList<>();
            // 规格
            StoreProductAttr storeProductAttr = new StoreProductAttr();
            storeProductAttr.setAttrName("规格");
            storeProductAttr.setType(0);
            storeProductAttr.setAttrValues("默认");
            storeProductAttr.setBarCode(barCode);
            attrList.add(storeProductAttr);

            // value对象
            StoreProductAttrValueRequest storeProductAttrValue = new StoreProductAttrValueRequest();
            storeProductAttrValue.setSourceSkuId(product.getGoodsItem());
            storeProductAttrValue.setStock(product.getStock());
            storeProductAttrValue.setPrice(price);
            storeProductAttrValue.setImage("");
            storeProductAttrValue.setCost(price);
            storeProductAttrValue.setSourceCost(price);
            storeProductAttrValue.setBarCode(barCode);
            storeProductAttrValue.setOtPrice(otPrice);
            // 非跨境商品
            if (product.getIsCrossBorder() == 1) {
                storeProductAttrValue.setTempId(StockAreaTempEnum.CN.getTempId());
            } else {
                // TODO 跨境商品发货地
                storeProductAttrValue.setTempId(StockAreaTempEnum.CN.getTempId());
            }
            LinkedHashMap<String, String> linkedMap = new LinkedHashMap<>();
            linkedMap.put("尺寸", "默认");

            storeProductAttrValue.setSuk("默认");
            storeProductAttrValue.setAttrValue(linkedMap);
            attrValueList.add(storeProductAttrValue);

            productRequest.setExchangeRate(priceResult.getExchangeRate());
            productRequest.setAttr(attrList);
            productRequest.setAttrValue(attrValueList);
            // 强制写一个 商户id 作为buyer商品标识标识
            productRequest.setMerId(CrmebMerchantEnums.HIQER.getMerchantId());
            productRequest.setKeyword(keyword);
            productRequest.setStoreInfo(product.getDescription());
            productRequest.setContent(product.getDescription());
            productRequest.setStoreName(product.getGoodsName());
            if(null != storeBrand) {
                productRequest.setBrandId(storeBrand.getId());
                productRequest.setBrandName(storeBrand.getEnName());
            }
            productRequest.setPrice(price);
            productRequest.setOtPrice(otPrice);
            productRequest.setCost(price);
            productRequest.setSourceCost(price);
            productRequest.setPromoteFlag(false);
            productRequest.setErpPromFlag(true);
            productRequest.setTempId(StockAreaTempEnum.CN.getTempId());

            productRequest.setBarCode(barCode);
            // 分类
            CategoryMatch categoryMatch = categoryMatchService.getOne(Wrappers.<CategoryMatch>lambdaQuery()
                    .eq(CategoryMatch :: getType, CategoryTypeEnum.HIQER)
                    .eq(CategoryMatch :: getOthCategoryName, product.getCategoryName())
                    .last("LIMIT 1")
                    );
            categoryMatchService.unMatchCategory(categoryMatch,null,product.getCategoryName(),null,CategoryTypeEnum.HIQER);
            // 复制重量
            if(null != categoryMatch) {
            	CategoryMatch supCategoryMatch = categoryMatchService.getById(categoryMatch.getCategoryId());
            	categoryMatch.setWeight(Optional.ofNullable(supCategoryMatch).orElse(new CategoryMatch()).getWeight());
            }
            Integer categoryId = null != categoryMatch ? categoryMatch.getCategoryId() : 1859;
            productRequest.setCateId(categoryId);
            productRequest.setCateIds(Arrays.asList(categoryId));
            productRequest.setWeight(null != categoryMatch ? categoryMatch.getWeight() : product.getGrossWeight());
            // TODO 商品图片暂时没有
//            productRequest.setImage(mainImage);
//            if(gallery.size() > 0) {
//                productRequest.setSliderImage(JSON.toJSONString(gallery));
//            }
            productRequest.setIsShow(true);
            productRequest.setSpecType(false);
            productRequest.setIsEurope(ProductTypeEnum.HIQER.getCode());
            productRequest.setUnitName(product.getGoodsUnitText());
            productRequest.setLastPushTime(new Date());
            productRequest.setAddTime(Integer.parseInt(String.valueOf(System.currentTimeMillis() / 1000L)));
            productRequest.setColorCode("");
            productRequest.setSeasonCode("");
        } catch (Exception e) {
            e.printStackTrace();
        }
        
        return productRequest;
    }

}
